var $;
var letterId;
layui.config({
    base : "../../js/"
}).use(['form','layer','layedit'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : parent.layer,
        layedit = layui.layedit;
    $ = layui.jquery;

    //消息回复
    var editIndex = layedit.build('msgReply',{
        tool: ['face'],
        height:100
    });
  /*  form.on('select(selectMsg)',function(data){
        var len = $(".msgHtml tr").length;
        for(var i=0;i<len;i++){
            if(data.value == "0"){
                $(".msgHtml tr").eq(i).show();
                $(".msgHtml tr.no_msg").remove();
            }else{
                if($(".msgHtml tr").eq(i).find(".msg_collect i").hasClass("icon-star")){
                    $(".msgHtml tr").eq(i).show();
                }else{
                    $(".msgHtml tr").eq(i).hide();
                }
            }
        }
        if(data.value=="1" && $(".msgHtml tr").find(".msg_collect i.icon-star").length=="0"){
            $(".msgHtml").append("<tr class='no_msg' align='center'><td colspan='4'>暂无收藏消息</td></tr>")
        }
    })*/

    //加载数据
    $.ajax({
        url: "selectLetter/"+ $("#hId").val() ,
        post:"GET",
        success :function(result){
            console.log(result);
            var msgHtml = '';
            data = result.extend.letterList;
            for(var i=0; i<data.length; i++){
                msgHtml += '<tr>';
                msgHtml += '  <td class="msg_info">';
                msgHtml += '    <img src="'+data[i].writerUser.picture+'" width="50" height="50"><input type="hidden" value="'+data[i].letterId+'">';
                msgHtml += '    <div class="user_info">';
                msgHtml += '        <h2 style="font-size: 15px">'+data[i].writerUser.nickName+'</h2>';
                msgHtml += '        <p>'+data[i].content+'</p>';
                msgHtml += '    </div>';
                msgHtml += '  </td>';
                msgHtml += '  <td class="msg_time">'+data[i].sendTime+'</td>';
                msgHtml += '  <td class="msg_reply"></td>';
                msgHtml += '  <td class="msg_opr">';
                msgHtml += '    <a class="layui-btn layui-btn-mini layui-btn-normal msg_collect" onclick="isRead(this)"><i class="layui-icon">&#xe600;</i> 已读</a>';
                msgHtml += '    <a class="layui-btn layui-btn-mini reply_msg"><i class="layui-icon">&#xe611;</i> 回复</a>';
                msgHtml += '  </td>';
                msgHtml += '</tr>';
            }
            $(".msgHtml").html(msgHtml);
        }
    })


    //回复
    $("body").on("click",".reply_msg,.msgHtml .user_info h2,.msgHtml .msg_info>img",function(){
        letterId = $(this).parents("tr").find("input[type=hidden]").val();
        var userName = $(this).parents("tr").find(".user_info h2").text();
        var index = layui.layer.open({
            title : "与 "+userName+" 的聊天",
            type : 2,
            content : "messageReply?letterId="+letterId,
            success : function(layero, index) {
                layui.layer.tips('点击此处返回消息列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
                var body = layui.layer.getChildFrame('body', index);
                //加载回复信息
                $.ajax({
                    url: "getLetterById",
                    post: "GET",
                    data: {letterId: letterId},
                    success: function (result) {
                        if (result.code == 100) {
                            console.log(result);
                            var msgReplyHtml = '';
                            var data = result.extend.letterList;
                            for (var i = 0; i < data.length; i++) {
                                msgReplyHtml += '<tr>';
                                msgReplyHtml += '  <td class="msg_info">';
                                msgReplyHtml += '    <img src="' + data[i].writerUser.picture + '" width="50" height="50">';
                                msgReplyHtml += '    <div class="user_info">';
                                msgReplyHtml += '        <h2>' + data[i].writerUser.nickName + '</h2>';
                                msgReplyHtml += '        <p>' + data[i].content + '</p>';
                                msgReplyHtml += '    </div>';
                                msgReplyHtml += '  </td>';
                                msgReplyHtml += '  <td class="msg_time">' + data[i].sendTime + '</td>';
                                msgReplyHtml += '  <td class="msg_reply"></td>';
                                msgReplyHtml += '</tr>';
                            }
                            body.find(".msgReplyHtml").html(msgReplyHtml);
                        }

                    }
                })
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        $(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);
    })

    //提交回复
    var message = [];
    $(".send_msg").click(function(){
        var content = layedit.getContent(editIndex);
        if(content != ''){
            $.ajax({
                url:"insertLetterReply",
                type:"get",
                data:{
                    "userId":userId,
                    "content":content,
                    "letterId":letterId,
                    "writer":writer
                },
                success:function (result) {
                    if (result.code == 100){
                        layer.msg("回复成功",{offset:'300px'});
                        var data = result.extend.letter;
                        var replyHtml = '';
                        replyHtml += '<tr>';
                        replyHtml += '  <td class="msg_info">';
                        replyHtml += '    <img src="'+data.writerUser.picture+'" width="50" height="50">';
                        replyHtml += '    <div class="user_info">';
                        replyHtml += '        <h2>'+data.writerUser.nickName+'</h2>';
                        replyHtml += '        <p>'+layedit.getContent(editIndex)+'</p>';
                        replyHtml += '    </div>';
                        replyHtml += '  </td>';
                        replyHtml += '  <td class="msg_time">'+formatTime(new Date())+'</td>';
                        replyHtml += '  <td class="msg_reply"></td>';
                        replyHtml += '</tr>';
                        $(".msgReplyHtml").prepend(replyHtml);
                        $("#LAY_layedit_1").contents().find("body").html('');
                    } else {
                        layer.msg("回复失败",{offset:'300px'});
                    }
                }
            })
        }else{
            layer.msg("请输入回复信息",{offset:'300px'});
        }
    })
})


function isRead(obj){
    var letterId = $(obj).parent().siblings().eq(0).find("input[type='hidden']").val();

    $.ajax({
        url:"isRead",
        type:"get",
        data:{
            "letterId":letterId
        },
        success:function (result) {
            if (result.code == 100) {
                $(obj).parents("tr").remove();
                $(".bubble").text($(".bubble").text()-1);
                layer.msg("已读私信",{offset:'300px' });
            }else{
                layer.msg("发生未知错误",{offset:'300px' });
            }
        }
    })
}


function formatTime(_time){
    var year = _time.getFullYear();
    var month = _time.getMonth()+1<10 ? "0"+(_time.getMonth()+1) : _time.getMonth()+1;
    var day = _time.getDate()<10 ? "0"+_time.getDate() : _time.getDate();
    var hour = _time.getHours()<10 ? "0"+_time.getHours() : _time.getHours();
    var minute = _time.getMinutes()<10 ? "0"+_time.getMinutes() : _time.getMinutes();
    return year+"-"+month+"-"+day+" "+hour+":"+minute;
}

